package com.linkage.seapeak.activity.user;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.linkage.jz.bankruptcy.R;
import com.linkage.seapeak.base.BaseActivity;
import com.linkage.seapeak.pojo.UploadImage;
import com.linkage.seapeak.utils.FileUtils;
import com.linkage.seapeak.utils.MenuBottomSheetDialog;
import com.linkage.seapeak.utils.ToastUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import uk.co.senab.photoview.PhotoView;

public class NewImageShowActivity extends BaseActivity {

    public static int IMAGE_REQUEST = 0xff;

    public static int CAMERA_REQUEST = 0xf1;
    public static int PIC_SELECT_REQUEST = 0xf2;

    public static int FROM_PERSON = 0x1;
    public static int FROM_SINGLE_SHOW = 0x2;

    public static int FROM_MUlTI_SHOW = 0x3;
    public static int FROM_MUlTI_EDIT = 0x4;

    TextView titleView;
    PhotoView image;
    ViewPager viewPager;
    PagerAdapter adapter;

    private static String imageUrl = "";
    ArrayList<Object> urlList = new ArrayList<>();

    //    记录修改图片地址的path
    static String imagePath = "";

    int fromType = FROM_SINGLE_SHOW;
    int index = 0;
     static String mdownloadUrl = "";

    public static void start(Activity context, String url,String downloadUrl) {
        Intent intent = new Intent(context, NewImageShowActivity.class);
//        intent.putExtra("image_url", url);
//        intent.putExtra("from_type", fromType);
        mdownloadUrl = downloadUrl;
        imageUrl = url;

        context.startActivityForResult(intent, IMAGE_REQUEST);
    }

    public static void start(Activity context, String url, int fromType) {
        Intent intent = new Intent(context, NewImageShowActivity.class);
        intent.putExtra("image_url", url);
        intent.putExtra("from_type", fromType);
        context.startActivityForResult(intent, IMAGE_REQUEST);
    }

    public static void start(Activity context, ArrayList urlList, int index, int fromType) {
        Intent intent = new Intent(context, NewImageShowActivity.class);
        intent.putExtra("url_list", urlList);
        intent.putExtra("index", index);
        intent.putExtra("from_type", fromType);
        context.startActivityForResult(intent, IMAGE_REQUEST);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.TRANSPARENT);
        }

//        imageUrl = getIntent().getStringExtra("image_url");
//        urlList = (ArrayList<Object>) getIntent().getSerializableExtra("url_list");
//        index = getIntent().getIntExtra("index", 0);
//        fromType = getIntent().getIntExtra("from_type", FROM_SINGLE_SHOW);

        setContentView(R.layout.activity_image_show);
        init();
    }

    private void init() {
        findViewById(R.id.icon_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleView = findViewById(R.id.activity_title);
        titleView.setText(fromType == FROM_PERSON ? "个人头像" : "图片详情");
        findViewById(R.id.action_menu).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (fromType == FROM_PERSON) {
                    showPersonDialog();
                } else if (fromType == FROM_SINGLE_SHOW) {
                    showNetImageDialog();
                } else if (fromType == FROM_MUlTI_SHOW) {
                    showMultiImageDialog();
                } else if (fromType == FROM_MUlTI_EDIT) {
                    showEditMultiImageDialog();
                }
            }
        });
        image = findViewById(R.id.image);
        viewPager = findViewById(R.id.image_pager);


        if (fromType == FROM_PERSON || fromType == FROM_SINGLE_SHOW) {
            image.setVisibility(View.VISIBLE);
            Glide.with(this).load(imageUrl)
                    .placeholder(R.drawable.icon_stub)
                    .into(image);
        } else {
            viewPager.setVisibility(View.VISIBLE);
            adapter = new PagerAdapter() {
                @Override
                public int getCount() {
                    return urlList == null ? 0 : urlList.size();
                }

                public int getItemPosition(Object object) {
                    return POSITION_NONE;
                }

                @NonNull
                @Override
                public Object instantiateItem(@NonNull ViewGroup container, int position) {
                    PhotoView view = new PhotoView(NewImageShowActivity.this);
                    String url = "";
                    if (urlList.get(index) instanceof String)
                        url = (String) urlList.get(position);
                    else if (urlList.get(index) instanceof UploadImage)
                        url = ((UploadImage) urlList.get(position)).getLoadUrl();
                    Glide.with(NewImageShowActivity.this).load((String) url)
                            .placeholder(R.drawable.icon_stub)
                            .into(view);
                    container.addView(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    return view;
                }

                @Override
                public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
                    container.removeView((View) object);
                }

                @Override
                public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                    return view == object;
                }
            };
            viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int i, float v, int i1) {

                }

                @Override
                public void onPageSelected(int i) {
                    index = i;
                }

                @Override
                public void onPageScrollStateChanged(int i) {

                }
            });
            viewPager.setAdapter(adapter);
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    viewPager.setCurrentItem(index);
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == CAMERA_REQUEST) {
                Bundle bundle = data.getExtras();
                // 获取相机返回的数据，并转换为图片格式
                Bitmap bitmap = (Bitmap) bundle.get("data");
                try {
                    File cameraPic = FileUtils.saveBitmapToTempFile(bitmap);
                    imagePath = cameraPic.getAbsolutePath();
                    Glide.with(this).load(cameraPic)
                            .into(image);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                ContentResolver contentResolver = getContentResolver();
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(data.getData()));
                    File cameraPic = FileUtils.saveBitmapToTempFile(bitmap);
                    imagePath = cameraPic.getAbsolutePath();
                    Glide.with(this).load(cameraPic)
                            .into(image);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void finish() {
        if (!TextUtils.isEmpty(imagePath)) {
            Intent intent = new Intent();
            intent.putExtra("imagePath", imagePath);
            setResult(RESULT_OK, intent);
        }
        if (urlList != null) {
            Intent intent = new Intent();
            intent.putExtra("urlList", urlList);
            setResult(RESULT_OK, intent);
        }
        super.finish();
    }

    // 提示用户该请求权限的弹出框
    private void showDialogTipUserRequestPermission() {

        new AlertDialog.Builder(this)
                .setTitle("存储权限不可用")
                .setMessage("由于需要获取存储空间，为你存储个人信息；\n否则，您将无法正常使用")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @TargetApi(Build.VERSION_CODES.M)
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        requestPermissions(new String[]{Manifest.permission.CAMERA}, 321);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    // 提示用户去应用设置界面手动开启权限

    private void showDialogTipUserGoToAppSettting() {
        new AlertDialog.Builder(this)
                .setTitle("存储权限不可用")
                .setMessage("请在-应用设置-权限-中，允许APM使用存储权限来保存用户数据")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);

        startActivityForResult(intent, 123);
    }

    // 用户权限 申请 的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    if (!b) {
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    }
                } else {
                    showToast("权限获取成功", ToastUtil.TOAST_TYPE.SUCCESS);
                    Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(camera, CAMERA_REQUEST);
                }
            }
        }
    }

    /**
     * 个人头像的时候弹窗
     */
    private void showPersonDialog() {
        final MenuBottomSheetDialog dialog = new MenuBottomSheetDialog(NewImageShowActivity.this);
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("拍照", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    // 检查该权限是否已经获取
                    int i = checkSelfPermission(Manifest.permission.CAMERA);
                    // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        // 如果没有授予该权限，就去提示用户请求
                        dialog.dismiss();
                        showDialogTipUserRequestPermission();
                        return;
                    }
                }

                Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(camera, CAMERA_REQUEST);
                dialog.dismiss();
            }
        }));
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("相册", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent picture = new Intent(Intent.ACTION_PICK,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(picture, PIC_SELECT_REQUEST);
                dialog.dismiss();
            }
        }));
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("保存", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(imagePath))
                    FileUtils.saveNetImageToGallery(NewImageShowActivity.this, imageUrl);
                else
                    FileUtils.copyImageToGallery(NewImageShowActivity.this, imagePath);
                dialog.dismiss();
            }
        }));
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("取消", 0xffff5555, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        }));
        dialog.show();
    }

    /**
     * 网络图片时候弹窗
     */
    private void showNetImageDialog() {
        final MenuBottomSheetDialog dialog = new MenuBottomSheetDialog(NewImageShowActivity.this);
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("保存", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FileUtils.saveNetImageToGallery(NewImageShowActivity.this, mdownloadUrl);
                dialog.dismiss();
            }
        }));
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("取消", 0xffff5555, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        }));
        dialog.show();
    }


    /**
     * 多张图片时候弹窗
     */
    private void showMultiImageDialog() {
        final MenuBottomSheetDialog dialog = new MenuBottomSheetDialog(NewImageShowActivity.this);
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("保存", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "";
                if (urlList.get(index) instanceof String)
                    url = (String) urlList.get(index);
                else if (urlList.get(index) instanceof UploadImage)
                    url = ((UploadImage) urlList.get(index)).getLoadUrl();

                FileUtils.saveNetImageToGallery(NewImageShowActivity.this, url);
                dialog.dismiss();
            }
        }));
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("取消", 0xffff5555, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        }));
        dialog.show();
    }

    /**
     * 编辑多张图片时候弹窗
     */
    private void showEditMultiImageDialog() {
        final MenuBottomSheetDialog dialog = new MenuBottomSheetDialog(NewImageShowActivity.this);
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("删除", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                urlList.remove(index);
                if (index == urlList.size())
                    index--;
                adapter.notifyDataSetChanged();
                dialog.dismiss();
                if (urlList.size() == 0)
                    finish();
            }
        }));
        dialog.addItem(new MenuBottomSheetDialog.DialogMenuItem("取消", 0xffff5555, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        }));
        dialog.show();
    }
}
